import Vue from 'vue'
import Vuex from 'vuex'
import { Base64 } from 'js-base64'
import routeDefine from './route-define.js';

Vue.use(Vuex)


// 根据地址栏记忆的base64编码还原为tab可用的数据结构
const translateTabData = (code) => {
  const tabs = JSON.parse(Base64.decode(code));
  const ret = [];
  tabs.forEach(item => {
    const tabObj = {
      flag: item[0],
      title: item[1],
      components: item[2].map(compData => {
        const comp = compData.split(':');
        const queryString = comp[1];
        const query = {};
        queryString.split(',').forEach(qr => {
          const qrValue = qr.split('=');
          query[qrValue[0]] = qrValue[1];
        });
        return {
          name: comp[0],
          query,
        };
      }),
    };
    ret.push(tabObj);
  });
  return ret;
};

// 简化tab数据结构
const zipTabData = (tabs) => {
  const ret = [];
  tabs.forEach(tab => {
    const components = tab.components.map(item => {
      const temp = [];
      for (const k in item.query) {
        temp.push(`${k}=${item.query[k]}`);
      } 
      return `${item.name}:${temp.join(',')}`;
    });
    ret.push([tab.flag, tab.title, components]);
  });
  return ret;
};

// 根据菜单唯一标识获取组件名
const getComponentNameByFlag = (flag) => {
  const route = routeDefine.find(item => flag === item.meta.from);
  return route ? route.name : null;
};

/*
const defaultComponent = {
  title: '首页',
  flag: 'welcome', // 菜单唯一标识
  components: [{
    name: 'welcome',
  }],
};
*/

export default new Vuex.Store({
  state: {
    isLogin: true,
    fullscreen: false,
    spinning: false, // 页面加载提示
    openedTabs: [],
    activedTabFlag: '',
    isRecordTab: true, // 记录tab状态，刷新页面可从url恢复
  },
  getters: {
    __getTabQuery(state) {
      let ret = {};
      const activedTab = state.openedTabs.find(item => item.flag === state.activedTabFlag);
      if (activedTab) {
        const currentComp = activedTab.components[activedTab.components.length - 1];
        if (currentComp) {
          ret = currentComp.query;
        }
      }
      return ret;
    },
  },
  mutations: {
    __addTab(state, payload) {
      const existTab = state.openedTabs.find(item => item.flag === payload.flag);
      if (existTab) {
        state.activedTabFlag = existTab.flag;
        if (payload._from !== 'menu') { // 非菜单触发的tab激活，重载一次组件
          existTab.components[existTab.components.length - 1].query = payload.query || {};
          const compList = existTab.components;
          existTab.components = [];
          Vue.nextTick(() => {
            existTab.components = compList;
          });
        }
      } else {
        const compName = getComponentNameByFlag(payload.flag);
        if (compName) {
          state.openedTabs.push({
            title: payload.title,
            flag: payload.flag,
            components: [{
              name: getComponentNameByFlag(payload.flag),
              query: payload.query || {},
            }],
          });
          state.activedTabFlag = payload.flag;
        } else {
          console.log(`[tab router] 没有找到对应的组件:${payload.flag}`);
        }
      }
      this.commit('__setTabHash');
    },
    __removeTab(state, payload) {
      state.openedTabs = state.openedTabs.filter(item => item.flag !== payload);
      if (state.activedTabFlag === payload && state.openedTabs.length > 0) {
        state.activedTabFlag = state.openedTabs[0].flag;
      }
      this.commit('__setTabHash');
    },
    __pushTab(state, payload) {
      const activedTab = state.openedTabs.find(item => item.flag === state.activedTabFlag);
      activedTab.components.push(payload);
      this.commit('__setTabHash', true); // true代表产生历史记录
    },
    __showTab(state, payload) {
      state.activedTabFlag = payload;
      this.commit('__setTabHash');
    },
    __backTab(state, payload) {
      const activedTab = state.openedTabs.find(item => item.flag === state.activedTabFlag);
      const length = activedTab.components.length;
      if (length > payload) {
        activedTab.components = activedTab.components.slice(0, length - payload);
        this.commit('__setTabHash');
      }
    },
    __setTabHash(state, payload) {
      if (!state.isRecordTab) {
        return;
      }
     const zipTab = zipTabData(state.openedTabs);
     const code = Base64.encode(JSON.stringify(zipTab));
     const newHash = `#/frame?tab=${encodeURIComponent(code)}`;
     if (payload) {
        window.location.hash = newHash;
      } else {
        const newUrl = window.location.href.replace(/^(.+)#.+$/, `$1${newHash}`);
        window.location.replace(newUrl);
      }
    },
    __reshowTab(state, payload) {
      if (!state.isRecordTab) {
        return;
      }
      if (payload) {
        try {
          state.openedTabs = translateTabData(decodeURIComponent(payload));
          if (!state.activedTabFlag && state.openedTabs.length > 0) {
            state.activedTabFlag = state.openedTabs[0].flag;
          }
        } catch(err) {
          console.log(err);
        }
      }
    },
    setFullscreen(state, payload) {
      state.fullscreen = payload;
    },
  },
  actions: {

  }
})
